import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import { EnvelopeIcon } from '@heroicons/react/24/outline'
import { Link } from 'react-router-dom'
import PageHeader from '../components/PageHeader'
import { AuthAPI } from '../app/api'

const ForgotPasswordPage = () => {
  const [email, setEmail] = useState('')
  const [info, setInfo] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const mutation = useMutation({ mutationFn: AuthAPI.forgotPassword })

  return (
    <div className="space-y-6">
      <PageHeader title="找回密码" description="输入你的邮箱，我们会发送重置链接（15 分钟有效）。" />
      <section className="surface-card p-6">
        <form
          className="flex flex-col gap-4"
          onSubmit={async (e) => {
            e.preventDefault()
            setError(null)
            setInfo(null)
            try {
              await mutation.mutateAsync({ email })
              setInfo('如果邮箱存在，我们已发送重置链接，请查收邮件。')
            } catch (err) {
              setError(err instanceof Error ? err.message : '请求失败，请稍后重试。')
            }
          }}
        >
          <label className="flex flex-col gap-2 text-sm font-medium text-slate-600">
            邮箱
            <div className="relative">
              <span className="pointer-events-none absolute inset-y-0 left-3 flex items-center">
                <EnvelopeIcon className="h-5 w-5 text-slate-400" />
              </span>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="h-11 w-full rounded-2xl border border-slate-200 bg-white px-4 pl-11 text-sm text-slate-700 shadow-inner focus:border-blush-500 focus:outline-none focus:ring-2 focus:ring-blush-200"
                placeholder="lovely@note.app"
              />
            </div>
          </label>
          {info ? <p className="text-xs text-emerald-600">{info}</p> : null}
          {error ? <p className="text-xs text-red-500">{error}</p> : null}
          <button
            type="submit"
            className="w-full rounded-full bg-gradient-to-r from-blush-500 to-sky-500 px-6 py-3 text-sm font-semibold text-white disabled:cursor-not-allowed disabled:opacity-60"
            disabled={mutation.isPending}
          >
            {mutation.isPending ? '发送中…' : '发送重置邮件'}
          </button>
          <p className="text-center text-xs text-slate-400">
            想起密码了？<Link className="text-blush-500" to="/auth">返回登录</Link>
          </p>
        </form>
      </section>
    </div>
  )
}

export default ForgotPasswordPage

